package cn.yshujia.service.impl;

import cn.yshujia.domain.dto.PageDTO;
import cn.yshujia.domain.entity.TreeHole;
import cn.yshujia.domain.vo.PageVO;
import cn.yshujia.mapper.TreeHoleMapper;
import cn.yshujia.repository.ResourcesRepository;
import cn.yshujia.repository.TreeHoleRepository;
import cn.yshujia.utils.PageUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author YShuJia
 * @create 2024/4/23
 * @description 服务层
 */

@Service
public class TreeHoleServiceImpl extends ServiceImpl<TreeHoleMapper, TreeHole> implements IService<TreeHole> {
	
	@Resource
	private TreeHoleMapper mapper;
	
	@Resource
	private TreeHoleRepository repository;
	
	@Resource
	private ResourcesRepository resourcesRepository;
	
	public PageVO<TreeHole> page(PageDTO dto) {
		return repository.page(dto);
	}
	
	public PageVO<TreeHole> adminPage(PageDTO dto) {
		IPage<TreeHole> page = mapper.selectPage(new Page<>(dto.getCurrent(), dto.getSize()), null);
		// 创建VO集合
		if (!ObjectUtils.isEmpty(page) && !ObjectUtils.isEmpty(page.getRecords())) {
			return PageUtils.getPage(dto, page.getRecords(), page.getTotal());
		}
		return new PageVO<>();
	}
	
	@Transactional (rollbackFor = {Exception.class})
	public Boolean insert(TreeHole treeHole) {
		treeHole.setAvatar(resourcesRepository.selectRandomIcon().getUrl());
		repository.del();
		return mapper.insert(treeHole) > 0;
	}
	
	@Transactional (rollbackFor = {Exception.class})
	public Boolean remove(List<Long> ids) {
		int r = mapper.deleteByIds(ids);
		// 删除成功，删除缓存
		if (r > 0) {
			repository.del();
		}
		return r > 0;
	}
}